import json
import random
import sys

from idcard.identity import IdNumber


def create_phone():
    """
    获取自定义手机号
    :return:
    """
    # 第二位数字
    second = [3, 4, 5, 7, 8][random.randint(0, 4)]
    # 第三位数字
    third = {3: random.randint(0, 9),
             4: [5, 7, 9][random.randint(0, 2)],
             5: [i for i in range(10) if i != 4][random.randint(0, 8)],
             7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],
             8: random.randint(0, 9), }[second]
    # 最后八位数字
    suffix = random.randint(9999999, 100000000)
    # 拼接手机号
    return "1{}{}{}".format(second, third, suffix)


def get_formatted_results(search_results):
    formatted_results = []
    for item in search_results:
        result = {
            "title": item["name"],
            "arg": item["name"],
            "icon": {
                "path": item["path"]
            }
        }
        formatted_results.append(result)
    return formatted_results


def get_alfred_items(search_results):
    if len(search_results) == 0:
        result = {
            "title": "类型不存在",
            "subtitle": "请输入：mobile/idcard",
        }
        return [result]
    else:
        return get_formatted_results(search_results)


if __name__ == '__main__':
    args = sys.argv[1]
    code_type = ''
    num = 1
    if ' ' in args:
        params = args.split(' ')
        for param in params:
            item = param.replace('\\', '')
            if item:
                if not code_type:
                    code_type = item
                else:
                    num = int(item)
                    break
    results = []
    if code_type == 'mobile':
        for i in range(num):
            mobile = create_phone()
            results.append({"name": mobile, "path": "mobile.jpg"})
    elif code_type == 'idcard':
        for i in range(num):
            # 随机生成男(1)或女(0)
            random_sex = random.randint(0, 1)
            idcard = IdNumber.generate_id(random_sex)
            results.append({"name": idcard, "path": "idcard.jpg"})
    alfred_json = json.dumps({
        "items": get_alfred_items(results)
    }, indent=2)
    print(alfred_json)
